// pages/partnercenter/extensionlist/extensionlist.js  fans_product
var shihan = require('../../../common/fetch')
var config = require('../../../common/config')
var app = getApp()
var winScale = 750 / app.data.deviceInfo.windowWidth
var range
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    page_size: 20,
    currentTab: 0,
    goods_canvas_flag: true,
    theme_canvas_flag: true,
    toast_flag: false,
    favoritelistflag: true,
    showLoading: true,
    favoritelist: [],
    share_money: '',
    painting: {},
    shareImage: '',
    res_navbar: ['我的清单', '世瀚推荐', '专题推荐']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    wx.hideShareMenu()
    const downloadmask = wx.downloadFile({
      url: 'https://img-oss.shihanbainian.com/upload_dev/images/c/1/1/c11c29e051123425362714a579c38028.jpg',
      success: function (res) {
        that.setData({
          theme_cardbg: res.tempFilePath
        })
      }
    })
    const downloadmask_1 = wx.downloadFile({
      url: 'https://img-oss.shihanbainian.com/upload_dev/images/b/2/3/b23e8f54e6ffb22ebb9705521cbc2470.jpg',
      success: function (res) {
        that.setData({
          goods_cardbg: res.tempFilePath
        })
      }
    })
    const downloadmask_2 = wx.downloadFile({
      url: 'https://img-oss.shihanbainian.com/upload_dev/images/c/1/e/c1e897cd54f1e0e69157fc47e5351d36.png',
      success: function (res) {
        that.setData({
          card_radius: res.tempFilePath
        })
      }
    })
    this.changefavoritelist(0);
    range = wx.getSystemInfoSync().windowHeight;
    var animation = wx.createAnimation({
      duration: 350,
      timingFunction: 'ease-in-out',
    });
    this.animation = animation;
  },
  onResNavbarTap: function(e) { //collectionrem_list
    this.setData({
      page: 1,
      card_code: '',
      cardFlag: false,
      favoritelist: [],
      showLoading: true,
      currentTab: e.currentTarget.dataset.index
    });
    this.changefavoritelist(this.data.currentTab);
  },
  changefavoritelist: function(tabindex) {
    switch (Number(tabindex)) {
      case 0:
        this.refreshfavoritelist(config.partner_favorite)
        break;
      case 1:
        this.refreshfavoritelist(config.partner_product_rem)
        break;
      case 2:
        this.refreshfavoritelist(config.collectionrem_list)
        break;
    }
  },
  refreshfavoritelist: function(a) {
    var that = this,
      url, data;
    var customerId = wx.getStorageSync('customerId');
    if (that.data.currentTab == 2) {
      data = {}
      url = a + that.data.page + '-' + that.data.page_size + '.html'
    } else {
      url = a
      data = {
        page: that.data.page,
        page_size: that.data.page_size
      }
    }
    shihan.sendRequest(url, 'POST', data)
      .then(function(response) {
        if (response.data.code == 0 && response.data.data.sh_items.length > 0) {
          for (var i = 0; i < response.data.data.sh_items.length; i++) {
            var productstr = response.data.data.sh_items[i]
            for (var c in productstr) {
              if (c&&c.indexOf("price") >= 0 && productstr[c]) {
                var pricestr = (JSON.stringify(productstr[c])).split('.')
                if (pricestr.length == 1) {
                  productstr[c] = productstr[c] + '.00'
                }
              }
            }
          }

          that.setData({
            page: that.data.page + 1,
            favoritelist: that.data.favoritelist.concat(response.data.data.sh_items),
            favoritelistflag: true,
            showLoading: false,
            prohasMore: true
          })
        } else {
          that.setData({
            favoritelistflag: false,
            showLoading: false,
            prohasMore: false
          })
        }
      }, function(error) {
        console.log(error);
      });
  },
  viewgoodsDetail: function(e) {
    wx.navigateTo({
      url: '/pages/goodsdetail/goodsdetail?goodsid=' + e.currentTarget.dataset.id
    })
  },
  jumpadvert: function(e) {
    app.AdSkipper(e, 1)
  },
  goodsdele: function(e) {
    var that = this
    shihan.sendRequest(config.add_extension, 'POST', {
        product_id: e.currentTarget.dataset.id
      })
      .then(function(response) {
        // console.log(response);
        if (response.data.code == 0) {
          that.setData({
            goodsinfo: that.data.goodsinfo
          })
          shihan.showToast.call(that, '删除推广清单成功');
          that.data.favoritelist.splice(e.currentTarget.dataset.index, 1);
          that.setData({
            favoritelist: that.data.favoritelist
          })
        }
      }, function(error) {
        console.log(error);
      });
  },
  openshare: function(e) {
    var that = this
    if (e.currentTarget.dataset.url) {
      this.setData({
        share_money: '',
        shareurl: e.currentTarget.dataset.url,
        shareimg: e.currentTarget.dataset.img,
        sharename: e.currentTarget.dataset.name,
        sharedetail: e.currentTarget.dataset.detail,
        sharetype: e.currentTarget.dataset.sharetype,
        showprice: e.currentTarget.dataset.showprice || '',
        lineprice: e.currentTarget.dataset.lineprice || '',
        codeimg: e.currentTarget.dataset.codeimg || 'https://img-oss.shihanbainian.com/shihan2/index/defaults.png'
      })
      const downloadmask = wx.downloadFile({
        url: that.data.shareimg,
        success: function (res) {
          that.setData({
            card_banner: res.tempFilePath
          })
          if (that.data.codeimg) {
            const downloadmask_1 = wx.downloadFile({
              url: that.data.codeimg,
              success: function (res) {
                that.setData({
                  card_code: res.tempFilePath
                })
                if (that.data.cardFlag) {
                  that.openshareimg()
                }
              }
            })
          }
        }
      })
      this.animation.translateY(-range).step();
      this.setData({
        animationData: this.animation.export()
      })
    }
  },
  closeshare: function() {
    this.animation.translateY(range).step();
    this.setData({
      refresh: true,
      animationData: this.animation.export()
    })
  },
  openshareimg: function() {
    var that = this;
    wx.showLoading({
      title: '绘制中'
    })
    if (this.data.card_code) {
      wx.hideLoading()
      if (this.data.sharetype == 'product') {
        this.drawGoodsCanvas(this)
      } else {
        this.drawThemeCanvas(this)
      }
    } else {
      this.setData({
        cardFlag: true
      })
    }
    // 此方法绘制有问题，汉子错位，以及大小不对
    // wx.showLoading({
    //   title: '绘制中',
    //   mask: true
    // })
    // that.setData({
    //   painting: {}
    // })
    // if (this.data.sharetype == 'product') {
    //   that.setData({
    //     painting: {
    //       width: 750,
    //       height: 1334,
    //       clear: true,
    //       views: [
    //         {
    //           type: 'image',
    //           url: 'https://img-oss.shihanbainian.com/upload_dev/images/b/2/3/b23e8f54e6ffb22ebb9705521cbc2470.jpg',
    //           top: 0,
    //           left: 0,
    //           width: 750,
    //           height: 1334
    //         },
    //         {
    //           type: 'image',
    //           url: that.data.shareimg,
    //           top: 60,
    //           left: 40,
    //           width: 670,
    //           height: 670
    //         },
    //         {
    //           type: 'image',
    //           url: 'https://img-oss.shihanbainian.com/upload_dev/images/c/1/e/c1e897cd54f1e0e69157fc47e5351d36.png',
    //           top: 60,
    //           left: 40,
    //           width: 670,
    //           height: 12
    //         },
    //         {
    //           type: 'image',
    //           url: that.data.codeimg,
    //           top: 983,
    //           left: 100,
    //           width: 250,
    //           height: 250
    //         },
    //         {
    //           type: 'text',
    //           content: that.data.sharename,
    //           fontSize: 40,
    //           color: '#222',
    //           textAlign: 'left',
    //           top: 770,
    //           left: 96,
    //           width: 558,
    //           MaxLineNumber: 1,
    //           breakWord: true,
    //           bolder: true
    //         },
    //         {
    //           type: 'text',
    //           content: that.data.sharedetail,
    //           fontSize: 28,
    //           color: '#999',
    //           textAlign: 'left',
    //           top: 840,
    //           left: 96,
    //           width: 558,
    //           lineHeight: 42,
    //           breakWord: true,
    //           MaxLineNumber: 2
    //         },
    //         {
    //           type: 'text',
    //           line: 1,
    //           margin: 10,
    //           content: '￥' + that.data.showprice,
    //           fontSize: 32,
    //           color: '#cc363c',
    //           textAlign: 'left',
    //           top: 1037,
    //           left: 393,
    //           bolder: true
    //         },
    //         {
    //           type: 'text',
    //           content: '￥' + that.data.lineprice,
    //           fontSize: 28,
    //           color: '#999',
    //           textAlign: 'left',
    //           top: 1042,
    //           left: 630.659375,
    //           textDecoration: 'line-through'
    //         },
    //         {
    //           type: 'text',
    //           content: '扫描或长按小程序码查看详情',
    //           fontSize: 28,
    //           color: '#222',
    //           textAlign: 'left',
    //           top: 1108,
    //           left: 392,
    //           lineHeight: 42,
    //           MaxLineNumber: 2,
    //           breakWord: true,
    //           width: 250
    //         }
    //       ]
    //     }
    //   })
    // } else {
    //   that.setData({
    //     painting: {
    //       width: 750,
    //       height: 1334,
    //       clear: true,
    //       views: [
    //         {
    //           type: 'image',
    //           url: 'https://img-oss.shihanbainian.com/upload_dev/images/c/1/1/c11c29e051123425362714a579c38028.jpg',
    //           top: 0,
    //           left: 0,
    //           width: 750,
    //           height: 1334
    //         },
    //         {
    //           type: 'image',
    //           url: that.data.shareimg,
    //           top: 160,
    //           left: 40,
    //           width: 670,
    //           height: 334
    //         },
    //         {
    //           type: 'image',
    //           url: 'https://img-oss.shihanbainian.com/upload_dev/images/c/1/e/c1e897cd54f1e0e69157fc47e5351d36.png',
    //           top: 60,
    //           left: 40,
    //           width: 670,
    //           height: 12
    //         },
    //         {
    //           type: 'image',
    //           url: that.data.codeimg,
    //           top: 874,
    //           left: 100,
    //           width: 250,
    //           height: 250
    //         },
    //         {
    //           type: 'text',
    //           content: that.data.sharename,
    //           fontSize: 40,
    //           color: '#222',
    //           textAlign: 'left',
    //           top: 554,
    //           left: 100,
    //           width: 548,
    //           MaxLineNumber: 1,
    //           breakWord: true,
    //           bolder: true
    //         },
    //         {
    //           type: 'text',
    //           content: that.data.sharedetail,
    //           fontSize: 28,
    //           color: '#999',
    //           textAlign: 'left',
    //           top: 634,
    //           left: 100,
    //           width: 544,
    //           lineHeight: 42,
    //           breakWord: true,
    //           MaxLineNumber: 4
    //         },
    //         {
    //           type: 'text',
    //           content: '扫描或长按小程序码查看详情',
    //           fontSize: 32,
    //           color: '#222',
    //           textAlign: 'left',
    //           top: 956,
    //           left: 392,
    //           lineHeight: 52,
    //           MaxLineNumber: 2,
    //           breakWord: true,
    //           width: 280
    //         }
    //       ]
    //     }
    //   })
    // }
  },
  drawThemeCanvas: function (that) {//生成专题卡片
    var context = wx.createCanvasContext("theme_canvas");
    var Ratio = app.data.deviceInfo.pixelRatio
    context.clearRect(0, 0, 750 / winScale, 1126 / winScale);
    context.setFillStyle("#fff");
    context.fillRect(0, 0, 750 / winScale, 1126 / winScale);//填充白色

    context.drawImage(that.data.theme_cardbg, 0, 0, 750 / winScale, 1334 / winScale);//画卡片背景
    context.drawImage(that.data.card_banner, 40 / winScale, 160 / winScale, 670 / winScale, 334 / winScale);//画banner
    context.drawImage(that.data.card_radius, 40 / winScale, 160 / winScale, 670 / winScale, 12 / winScale);//画圆角

    var labeltit1 = new String(that.data.sharename);
    var text1 = "";
    var newtext1 = labeltit1.split("");
    for (var i = 0; i <= labeltit1.length; i++) {
      if (i <= 12 && newtext1[i]) {
        text1 = text1 + newtext1[i];
      }
    }
    if (labeltit1.length > 12) {
      text1 = text1 + '...'
    }
    context.fillStyle = "#222";
    context.setFontSize(40 / winScale);
    context.setTextAlign('center');
    context.fillText(text1, 375 / winScale, 594 / winScale);

    var text2 = "";
    var count = 0;
    var begin_width = 100 / winScale;
    var begin_height = 660 / winScale;
    var labeltit2 = new String(that.data.sharedetail);

    context.fillStyle = "#999";
    context.setFontSize(28 / winScale);
    context.setTextAlign('left');
    var stringLenght = labeltit2.length;
    var newtext2 = labeltit2.split("");
    var flag = false
    for (var i = 0; i <= stringLenght; i++) {
      if (i <= 60) {
        var a = (i == 59 ? 19 : 20)
        if (count == a) {
          if (flag) {
            context.fillText(text2, begin_width, begin_height);
          } else {
            context.fillText(text2, begin_width, begin_height);
          }
          begin_height = begin_height + 24;
          text2 = "";
          count = 0;
          flag = true
        }
        if (i == stringLenght) {
          if (i <= 20) {
            context.setTextAlign('center');
            context.fillText(text2, 375 / winScale, begin_height);
          } else {
            context.fillText(text2, begin_width, begin_height);
          }
        }
        var text2 = text2 + newtext2[0];
        count++;
        newtext2.shift();
      }
    }

    context.drawImage(that.data.card_code, 100 / winScale, 873 / winScale, 250 / winScale, 250 / winScale);
    context.setTextAlign('left');
    context.fillStyle = "#222";
    context.setFontSize(32 / winScale);
    context.fillText("扫描或长按小程序码", 392 / winScale, 988 / winScale);
    context.fillText("查看详情", 392 / winScale, 1036 / winScale);
    context.restore();
    context.draw(false, function (e) {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        quality: 1,
        width: 750 / winScale,
        height: 1334 / winScale,
        destWidth: 750 * Ratio / winScale,
        destHeight: 1334 * Ratio / winScale,
        canvasId: "theme_canvas",
        success: function (res) {
          // that.setData({
          //   theme_canvas_flag: false
          // })
          console.log(res.tempFilePath)
          var imgarr = [];
          imgarr.push(res.tempFilePath)
          wx.hideLoading()
          wx.previewImage({
            urls: imgarr,
            success: function () {
              that.setData({
                hideimg: false,
                refresh: false,
                cardFlag: false
              })
              that.closeshare()
            }
          })
        }
      })
    })
  },
  drawGoodsCanvas: function (that) {//生成商品卡片
    var context = wx.createCanvasContext("goods_canvas");
    var Ratio = app.data.deviceInfo.pixelRatio
    context.clearRect(0, 0, 750 / winScale, 1334 / winScale);
    context.setFillStyle("#fff");
    context.fillRect(0, 0, 750 / winScale, 1334 / winScale);//填充白色

    context.drawImage(that.data.goods_cardbg, 0, 0, 750 / winScale, 1334 / winScale);//画卡片背景
    context.drawImage(that.data.card_banner, 40 / winScale, 60 / winScale, 670 / winScale, 670 / winScale);//画banner
    context.drawImage(that.data.card_radius, 40 / winScale, 60 / winScale, 670 / winScale, 12 / winScale);//画圆角

    var labeltit1 = new String(that.data.sharename);
    var text1 = "";
    var newtext1 = labeltit1.split("");
    for (var i = 0; i <= labeltit1.length; i++) {
      if (i <= 12 && newtext1[i]) {
        text1 = text1 + newtext1[i];
      }
    }
    if (labeltit1.length > 12) {
      text1 = text1 + '...'
    }
    context.fillStyle = "#222";
    context.setFontSize(40 / winScale);
    context.setTextAlign('center');
    context.fillText(text1, 375 / winScale, 810 / winScale);

    var text2 = "";
    var count = 0;
    var begin_width = 96 / winScale;
    var begin_height = 867 / winScale;
    var labeltit2 = new String(that.data.sharedetail);

    context.fillStyle = "#999";
    context.setFontSize(28 / winScale);
    context.setTextAlign('left');
    var stringLenght = labeltit2.length;
    var newtext2 = labeltit2.split("");
    var flag = false
    for (var i = 0; i <= stringLenght; i++) {
      if (i <= 40) {
        if (count == 20) {
          if (flag) {
            context.fillText(text2, begin_width, begin_height);
          } else {
            context.fillText(text2, begin_width, begin_height);
          }
          begin_height = begin_height + 24;
          text2 = "";
          count = 0;
          flag = true
        }
        if (i == stringLenght) {
          if (i <= 20) {
            context.setTextAlign('center');
            context.fillText(text2, 375 / winScale, begin_height);
          } else {
            context.fillText(text2, begin_width, begin_height);
          }
        }
        var text2 = text2 + newtext2[0];
        count++;
        newtext2.shift();
      }
    }

    context.drawImage(that.data.card_code, 100 / winScale, 983 / winScale, 250 / winScale, 250 / winScale);
    context.setTextAlign('left');
    context.fillStyle = "#cc363c";
    context.setFontSize(32 / winScale);
    context.fillText("¥", 392 / winScale, 1080 / winScale);
    var metrics1 = context.measureText('¥').width;
    context.setFontSize(42 / winScale);
    context.fillText(that.data.showprice, (392 / winScale) + metrics1, 1082 / winScale);
    var metrics2 = context.measureText(that.data.showprice).width;
    context.setStrokeStyle('#999')
    context.fillStyle = "#999";
    context.setFontSize(28 / winScale);
    context.fillText("¥" + that.data.lineprice, (402 / winScale) + metrics1 + metrics2, 1080 / winScale);
    var metrics3 = context.measureText("¥" + that.data.lineprice).width;
    context.beginPath()
    context.moveTo((402 / winScale) + metrics1 + metrics2, 1071 / winScale);
    context.lineTo((402 / winScale) + metrics1 + metrics2 + metrics3, 1071 / winScale);
    context.closePath()
    context.stroke()


    context.fillStyle = "#222";
    context.setFontSize(32 / winScale);
    context.fillText("扫描或长按小程序码", 392 / winScale, 1136 / winScale);
    context.fillText("查看详情", 392 / winScale, 1180 / winScale);
    context.restore();
    context.draw(false, function (e) {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        quality: 1,
        width: 750 / winScale,
        height: 1334 / winScale,
        destWidth: 750 * Ratio / winScale,
        destHeight: 1334 * Ratio / winScale,
        canvasId: "goods_canvas",
        success: function (res) {
          // that.setData({
          //   goods_canvas_flag: false
          // })
          console.log(res.tempFilePath)
          var imgarr = [];
          imgarr.push(res.tempFilePath)
          wx.hideLoading()
          wx.previewImage({
            urls: imgarr,
            success: function () {
              that.setData({
                hideimg: false,
                refresh: false,
                cardFlag: false
              })
              that.closeshare()
            }
          })
        }
      })
    })
  },
  eventGetImage: function (event) {
    // console.log(event)
    const { tempFilePath, errMsg } = event.detail;
    if (errMsg === 'canvasdrawer:ok') {
      this.setData({
        shareImage: tempFilePath
      })
    }
    this.previewImage(this.data.shareImage);
  },
  previewImage: function (url) {
    var that = this, imgarr = [];
    imgarr.push(url)
    wx.hideLoading()
    wx.previewImage({
      urls: imgarr,
      success: function () {
        that.closeshare();
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this
    if (that.data.favoritelistflag) {
      that.setData({
        favoritelistflag: false
      })
      this.changefavoritelist(this.data.currentTab)
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var that = this,
      shareurl;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target.dataset)
    }
    if (res.target.dataset.url) {
      shareurl = res.target.dataset.url
    } else {
      shareurl = that.data.shareurl
    }
    return {
      title: res.target.dataset.name,
      path: shareurl,
      imageUrl: res.target.dataset.img,
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  }
})